const express = require("express");
const route = express.Router();
const path = require("path")
const fs = require("fs");
//引入权限校验中间件
const isLoginMiddle = require("../middleware/isLoginMiddle")

const advModel = require("../db/model/advModel")

//主要是为了书写一个接口,使用我们封装好的权限验证中间件
route.delete("/deleteAdv", isLoginMiddle, async (req, res) => {
  const {
    _id
  } = req.query;

  //删除数据库对应的图片
  //首先去数据库查询当前的_id对应的图片名
  try {
    //首先去数据库查询当前的_id对应的图片名
    const {
      advHref
    } = await advModel.findOne({
      _id
    })

    const imgName = advHref.split("/")[2];

    //删除这个图片
    console.log(path.resolve(__dirname, "../upload", imgName));
    fs.unlink(path.resolve(__dirname, "../upload", imgName), () => {
      console.log("删除成功");
    })
  } catch (e) {
    console.log("删除图片逻辑有错" + e.message);
    return res.send({
      code: 10001,
      msg: "删除图片逻辑有错" + e.message,
      data: null
    })
  }


  //删除数据库的数据
  try {
    const deleteResult = await advModel.deleteOne({
      _id
    })

    res.send({
      code: 10000,
      msg: "删除广告列表成功",
      data: null
    })
  } catch (e) {
    console.log("删除广告列表失败" + e.message);
    res.send({
      code: 10001,
      msg: "删除广告列表失败" + e.message,
      data: null
    })
  }
})

module.exports = route;